package de.pa2.proxy;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Pattern;

public class UrlUtil {
	private static final Pattern URL_PATTERN = Pattern.compile(Pattern
			.quote("(http[s]?)://([^:/]*)(:[0-9]*)?((/)?.*)"));

	public static Url extract(String uri) {
		if (!uri.contains("://")) {
			// mail.google.com:443
			if (uri.contains(":")) {
				String[] tmp = uri.split(":");
				String port = tmp[1].split("/")[0];
				if ("443".equals(port)) {
					uri = "https://" + uri;
				}
			}
		}

		boolean secure = false;
		int port = 0;
		String hostname = null;
		String location = null;
		URL url = null;
		try {
			url = new URL(uri);
			hostname = url.getHost();
			location = url.getPath();
			port = url.getPort();
			secure = url.getProtocol().equals("https");
			if (port == -1) {
				if (secure)
					port = 443;
				else
					port = 80;
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Matcher m = URL_PATTERN.matcher(uri);
		// if (m.matches()) {
		// secure = "https".equals(m.group(1));
		// hostname = m.group(2);
		// String tmpPort = m.group(3);
		// if (tmpPort != null) {
		// port = Integer.parseInt(tmpPort.substring(1));
		// } else {
		// if (secure) {
		// port = 443;
		// } else {
		// port = 80;
		// }
		// }
		// location = m.group(4);
		// }
		return new Url(secure, hostname, port, location);
	}
}
